package com.xiyue.leaspring.action;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Collection;

@Controller
public class GlobalAction {

    private Logger logger = LoggerFactory.getLogger(GlobalAction.class);

    @Autowired
    private DefaultKaptcha captchaProducer;


    @RequestMapping("/loginPage")
    public String loginpage(){
        return "login";
    }

    @PreAuthorize("isAuthenticated()")
    @RequestMapping("/welcomePage")//访问路径
    public String welcome(){//登录成功路径
        Authentication authentication = SecurityContextHolder
                .getContext().getAuthentication();//获取认证对象
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();//用户详情
        String username = userDetails.getUsername();//获得用户名
        this.logger.info("用户名："+username);
        //通过userDetail对象获取当前用户的所有授权信息
        Collection<? extends GrantedAuthority> authorities =userDetails.getAuthorities();
        this.logger.info("授权信息："+authorities);
        return "welcome";//设置跳转路径
    }
    @RequestMapping("/logoutPage")
    public String logout(){
        return "logout";
    }

    @RequestMapping(value = "/randomCode")
    public ModelAndView kaptcha(){
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getResponse();
        HttpSession session = request.getSession();
        response.setHeader("Pragma","No-cache");//不缓存数据
        response.setHeader("Cache-Control","no-cache");//不缓存数据
        response.setDateHeader("Expires",0);//不失效
        response.setContentType("image/jpeg");//MIME类型
        String capText = captchaProducer.createText();//获取验证码上的文字
        //将验证码上的文字保存在Session中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        this.logger.info("验证码："+code);
        BufferedImage image = this.captchaProducer.createImage(capText);//图像
        try {
            OutputStream outputStream = response.getOutputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(image,"JPEG",bos);//图像输出
            byte[] buf = bos.toByteArray();
            response.setContentLength(buf.length);
            outputStream.write(buf);
            bos.close();
            outputStream.close();
        }catch (Exception e){

        }

        return null;
    }

}
